
import { Component, OnInit ,ViewChild } from '@angular/core';
import { NavController } from '@ionic/angular';
import { StorageService  } from '../../service/storage.service'
import { CommonService } from '../../service/common.service'

import { EventService } from '../../service/event.service'


@Component({
  selector: 'app-info',
  templateUrl: './info.page.html',
  styleUrls: ['./info.page.scss'],
})
export class InfoPage implements OnInit {

  @ViewChild('avatarInput') avatarInput;

  public PersonalInfo:any
  public disNk:boolean = false
  public nickname:string;
  public show:boolean = false
  
  constructor(public eventService:EventService,public nav: NavController,public storage:StorageService,public common:CommonService) { 
    
    // var str="antzone";
    // console.log(str.substring(1,3));
  }

  ngOnInit() {
    this.PersonalInfo = this.common.getInfo()
    // console.log(this.PersonalInfo)
  }

  back(){
    this.nav.navigateBack('/tabs/tab4');
  }

  changefile(e){
    // 上传文件
    var files = this.avatarInput.nativeElement.files;
    var formData = new FormData()
    // 记得去掉表头
    formData.append('file', files[0])
    if (files) {
      this.show=true
     
        var api = '/tbr/uploadImg'
        this.common.postbody(api,formData).then((response:any)=>{
            
            // 获取登录信息
            var apis = '/tbr/changeAvater'
            var params = {'url': response.msg,'nickname':this.PersonalInfo.nickname}
            
            this.common.post(apis,params,false).then((res:any)=>{
              if(res.code == 200){
                this.show=false
                this.PersonalInfo.avater = response.msg
                this.storage.set('PersonalInfo',this.PersonalInfo)
                this.common.presentToast('更新成功')
                
                //通知用户中心更新用户信息
                this.eventService.event.emit('useraction');
              }
            })
        })
    }
    if (files.length === 0) {
        return;
    }
}
  
  changePhoto(e) {
    // 触发上传图片按钮
    // console.log(e)
    this.avatarInput.nativeElement.dispatchEvent(new MouseEvent("click"))
  }

  // 昵称显示
  showNk(){
    this.disNk = !this.disNk
  }

  cancelNk(){
    this.disNk = false
  }

  events(){
    this.eventService.event.emit('useraction')
  }

  commitNk(){
    if(this.nickname == ""){
      this.common.presentAlert('昵称不能为空')
      return false
    }
    this.show=true
    // 获取登录信息
    var apis = '/tbr/changeAvater'
    var params = {'url': this.PersonalInfo.avater,'nickname':this.nickname}
    
    this.common.post(apis,params,false).then((res:any)=>{
      if(res.code == 200){
        this.show=false
        // console.log(res)
        this.PersonalInfo.nickname = this.nickname
        this.common.presentToast('更新成功')
        
        //通知用户中心更新用户信息
        this.events()
        this.disNk = false
        
      }else{
        this.disNk = false
      }
    })
  }

}

